<template>
  <v-menu
    v-if="showTranslateIndicator"
    v-model="showTranslatePanel"
    :close-on-content-click="false"
    :disabled="translationState === 'translating'"
    location="bottom"
    :offset="6"
  >
    <template #activator="{ props }">
      <v-btn
        v-bind="props"
        class="d-flex align-center mr-n3 cursor-pointer"
        :color="statusColor"
        density="comfortable"
        size="small"
        variant="text"
        @mousedown.stop
      >
        <v-progress-circular
          v-if="translationState === 'translating'"
          indeterminate
          size="14"
          width="2"
        />
        <v-icon v-else class="mr-1" :icon="mdiTranslate" size="16" />
        <span class="text-caption">{{ statusLabel }}</span>
      </v-btn>
    </template>
    <v-card min-width="300">
      <div class="translate-header d-flex align-center px-3 py-2">
        <v-icon class="mr-1" :icon="mdiTranslate" size="16" />
        <span class="text-medium-emphasis">{{ t('translate.title') }}</span>
        <v-spacer />
      </div>
      <v-card-text class="pt-2 pb-2 px-3">
        <div class="translate-row mb-2">
          <div class="translate-label text-caption text-medium-emphasis mb-1">
            {{ t('translate.toLabel') }}
          </div>
          <v-select
            v-model="toLang"
            class="flex-1 translate-select"
            hide-details
            item-title="title"
            item-value="value"
            :items="languageOptionsNoAuto"
            variant="outlined"
          />
        </div>
        <div class="d-flex justify-end mt-4">
          <v-btn class="mr-2" color="primary" size="small" @click="onTranslateClick">
            {{ t('translate.actions.translate') }}
          </v-btn>
          <v-btn size="small" variant="tonal" @click="onShowOriginalClick">
            {{ t('translate.actions.showOriginal') }}
          </v-btn>
        </div>
      </v-card-text>
    </v-card>
  </v-menu>
</template>

<script lang="ts" setup>
import { mdiTranslate } from '@mdi/js'
import { computed, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useLayoutStore } from '@/windows/layoutBrowser/stores/layout'
import { systemState } from 'global-state'

const layoutStore = useLayoutStore()
const { t } = useI18n()

const prop = defineProps<{
  tab: F2.tab.Entity
  // 简洁显示
  simple?: boolean
}>()

const showTranslatePanel = computed({
  get() {
    return layoutStore.showTranslatePanelIds.has(prop.tab.id)
  },
  set(value) {
    if (value) {
      layoutStore.showTranslatePanelIds.add(prop.tab.id)
    } else {
      layoutStore.showTranslatePanelIds.delete(prop.tab.id)
    }
  }
})

// 翻译状态与UI
const translationState = computed(() => prop.tab.state.translation ?? 'idle')
const showTranslateIndicator = computed(() => translationState.value !== 'idle')

const statusLabel = computed(() => t(`translate.status.${translationState.value}`))

const statusColor = computed(() => {
  switch (translationState.value) {
    case 'translating': {
      return 'warning'
    }
    case 'translated': {
      return 'success'
    }
    case 'failure': {
      return 'error'
    }
    default: {
      return ''
    }
  }
})

let targetLanguage = systemState.state.translationLanguage
if (!targetLanguage) {
  targetLanguage = String(systemState.state.language ?? 'en')
  if (targetLanguage === 'zhHans') {
    targetLanguage = 'zh-cn'
  }
}
const toLang = ref<string>(targetLanguage)

watch(toLang, () => {
  if (!showTranslatePanel.value) return
  showTranslatePanel.value = false
  onTranslateClick()
})

watch(
  () => systemState.state.translationLanguage,
  newLang => {
    if (newLang) {
      toLang.value = newLang
    }
  }
)

const languageOptions = computed(() => [
  { title: t('lang.auto'), value: 'auto' },
  { title: t('lang.english'), value: 'en' },
  { title: t('lang.chinese'), value: 'zh-cn' },
  { title: t('lang.japanese'), value: 'ja' },
  { title: t('lang.korean'), value: 'ko' },
  { title: t('lang.french'), value: 'fr' },
  { title: t('lang.german'), value: 'de' },
  { title: t('lang.spanish'), value: 'es' },
  // Southeast Asian languages
  { title: t('lang.vietnamese'), value: 'vi' },
  { title: t('lang.thai'), value: 'th' },
  { title: t('lang.khmer'), value: 'km' },
  { title: t('lang.indonesian'), value: 'id' },
  { title: t('lang.malay'), value: 'ms' },
  { title: t('lang.filipino'), value: 'tl' },
  { title: t('lang.burmese'), value: 'my' },
  { title: t('lang.lao'), value: 'lo' }
])

watch(
  () => prop.tab.id,
  () => {
    showTranslatePanel.value = false
  }
)

const languageOptionsNoAuto = computed(() => languageOptions.value.filter(i => i.value !== 'auto'))

function onTranslateClick() {
  showTranslatePanel.value = false
  systemState.set('translationLanguage', toLang.value)

  _pre_.tab.translatePage(toLang.value, prop.tab.webContentsId)
}

function onShowOriginalClick() {
  showTranslatePanel.value = false
  _pre_.tab.restoreOriginal(prop.tab.webContentsId)
}
</script>

<style scoped>
.translate-header {
  border-bottom: 1px solid rgba(var(--v-theme-on-surface), 0.06);
}
.translate-row {
  min-height: 32px;
}
.translate-label {
  line-height: 32px;
}
.translate-select :deep(.v-field) {
  height: 32px;
}
.translate-select :deep(.v-field__input) {
  min-height: 32px;
  padding-top: 0;
  padding-bottom: 0;
}
</style>

<i18n>
{
  "zhHans": {
    "translate": {
      "title": "翻译",
      "toLabel": "翻译为",
      "status": {
        "idle": "翻译",
        "translating": "翻译中",
        "translated": "已翻译",
        "failure": "翻译失败"
      },
      "actions": {
        "translate": "翻译",
        "showOriginal": "显示原文"
      }
    },
    "lang": {
      "auto": "自动检测",
      "english": "英语",
      "chinese": "中文 (简体)",
      "japanese": "日语",
      "korean": "韩语",
      "french": "法语",
      "german": "德语",
      "spanish": "西班牙语",
      "vietnamese": "越南语",
      "thai": "泰语",
      "khmer": "高棉语",
      "indonesian": "印度尼西亚语",
      "malay": "马来语",
      "filipino": "菲律宾语",
      "burmese": "缅甸语",
      "lao": "老挝语"
    }
  },
  "en": {
    "translate": {
      "title": "Translate",
      "toLabel": "Translate to",
      "status": {
        "idle": "Translate",
        "translating": "Translating",
        "translated": "Translated",
        "failure": "Translation failed"
      },
      "actions": {
        "translate": "Translate",
        "showOriginal": "Show original"
      }
    },
    "lang": {
      "auto": "Auto detect",
      "english": "English",
      "chinese": "Chinese (Simplified)",
      "japanese": "Japanese",
      "korean": "Korean",
      "french": "French",
      "german": "German",
      "spanish": "Spanish",
      "vietnamese": "Vietnamese",
      "thai": "Thai",
      "khmer": "Khmer",
      "indonesian": "Indonesian",
      "malay": "Malay",
      "filipino": "Filipino",
      "burmese": "Burmese",
      "lao": "Lao"
    }
  }
}
</i18n>
